import axios from 'axios'
import utils from './index'
import router from '@/router'
import { Message } from '../../node_modules/view-design'

// 默认配置
const request = axios.create({
  // baseURL: '/api',
  timeout: 8000
})

// 清空数据
function clearData() {
  router.push({
    path: '/login'
  })
}

// 创建报错
function errorCreate(data) {
  const err = new Error(data)
  Message.error(`${data}`)
  throw err
}

// 请求拦截
request.interceptors.request.use( (config) => {
  // 请求头中添加token
  config.headers['token'] = utils.getToken()

  // 将数据转化成 JSON字符串
  // if (config.method === 'post' && config.data) {
  //   config.data = JSON.stringify(config.data)
  // }

  return config
},
(error) => {
  console.log(error)
  Promise.reject(error)
 }
)

// 响应拦截
request.interceptors.response.use(
  (response) => {

    // 保存token
    if (response.headers.hasOwnProperty('token')) {
      utils.setToken(response.headers.token)
    }

    // 定义状态码 判断前端或者后端出错
    const code = response.data
    if(code === undefined) {
      errorCreate('状态错误')
    } else {
      switch(code) {
        case 20000:
          errorCreate('系统异常')
      }
    }
    if (response.data.status === 10000) {
      return response.data.data
    } else {
      if (response.data.status === 10007) {
        clearData()
      }
      errorCreate(response.data.msg)
    }
  },
  (error) => {
		if (error && error.response) {
			switch (error.response.status) {
				case 400:
					error.message = '请求错误'
					break
				case 401: {
					error.message = 'Token过期，请重新登录！'
					sessionStorage.setItem('token', '')
					break
				}
				case 403:
					error.message = '拒绝访问'
					break
				case 404:
					error.message = `请求地址出错: ${error.response.config.url}`
					break
				case 408:
					error.message = '请求超时'
					break
				case 500:
					error.message = '服务器内部错误'
					break
				case 501:
					error.message = '服务未实现'
					break
				case 502:
					error.message = '网关错误'
					break
				case 503:
					error.message = '服务不可用'
					break
				case 504:
					error.message = '网关超时'
					break
				case 505:
					error.message = 'HTTP版本不受支持'
					break
				default:
					break
			}
		}
		// errorLog(error)
		return Promise.reject(error)
	}
)

export default request